package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy*
 * @package: com.elite.groovy.callback*
 * @className: apiAPIFixChatData
 * @description: 网聊聊天数据修复处理。
 * @author: Tao
 * @date: 2024-05-19 15:00
 * @version: 1.0
 */
public class apiAPIFixChatData implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiAPIFixChatData.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData.put("code", -1);
            outData.put("message", "API被非法IP调用-Request Not Allow!" + IpAddressUtil.getIpAddress(request));
            log.warn(outData);
            return outData;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST" && getMethod != "GET") {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {
            // 解析请求报文
            JSONObject callJson = new JSONObject();

            List<Map<String, Object>> Chat_Message_List = jt.queryForList("Select Id, Chat_User_Id, Chat_Session_Id, Post_Time, From_Unixtime(Post_Time / 1000) As Send_Time From Chat_Message Where Ai_Text Is Null And Post_Time > Unix_Timestamp('2024-01-11 20:37:24') * 1000 Order By Post_Time Desc Limit 1000");

            for (int i = 0; i < Chat_Message_List.size(); i++) {
                // 获取Chat_Message信息
                String Chat_Session_Id = Chat_Message_List.get(i).get("Chat_Session_Id").toString();
                String Post_Time = Chat_Message_List.get(i).get("Post_Time").toString();
                String Send_Time = Chat_Message_List.get(i).get("Send_Time").toString();

                // 通过SessionID找到对应的坐席
                List<Map<String, Object>> Chat_Session_List = jt.queryForList("Select Agent_Id, Start_Time, Client_Id, Perm_Flag, Last_Queue_Id From Chat_Session Where Id = ?", Chat_Session_Id);
                log.debug(i + "# Chat_Session_List:" + Chat_Session_List);
                if (Chat_Session_List.size() > 0) {

                    String Client_Id = Chat_Session_List.get(0).get("Client_Id").toString();

                    // 找到用户ID
                    List<Map<String, Object>> Customer_List = jt.queryForList("Select Customer_Guid, Customer_Id From Customer Where Customer_Guid = ?", Client_Id);
                    log.debug(i + "# Customer_List:" + Customer_List);
                    if (Customer_List.size() > 0) {
                        String Customer_Id = Customer_List.get(0).get("Customer_Id").toString();

                        // 找到此前进线历史
                        List<Map<String, Object>> Chat_Inparams_List = jt.queryForList("Select Rec_Guid, Update_Time, Staff_Id From Dg_Chat_Inparams Where Update_Time <= ? And Userid = ? Order By Update_Time Desc Limit 1", Send_Time, Customer_Id);
                        log.debug(i + "# Chat_Inparams_List:" + Chat_Inparams_List);
                        if (Chat_Inparams_List.size() > 0) {
                            String Rec_Guid = Chat_Inparams_List.get(0).get("Rec_Guid").toString();
                            String Update_Time = Chat_Inparams_List.get(0).get("Update_Time").toString();

                            // 更新标记表
                            int update_Num = jt.update("Update Chat_Message Set Ai_Text = ? Where Chat_Session_Id = ? And Post_Time > Unix_Timestamp(?) * 1000 And Post_Time <= ?", Rec_Guid, Chat_Session_Id, Update_Time, Post_Time);

                            // 更新统计数据
                            String totalSQL = '''UPDATE Dg_Chat_Inparams R1,
                                                        (
                                                            SELECT
                                                                R1.Rec_Guid,
                                                                R3.Id,
                                                                Count(*) AS Chatnumber,
                                                                Sum(
                                                                IF
                                                                ( Length( R2.Chat_User_Id ) > 6, 1, 0 )) AS Custnumber,
                                                                Sum(
                                                                IF
                                                                ( Length( R2.Chat_User_Id ) <= 6, 1, 0 )) AS Staffnumber,
                                                                Max( R3.Perm_Flag ) AS Perm_Flag,
                                                                Sum(
                                                                IF
                                                                ( R2.POST_TIME > ifnull(R4.maxposttime,0) and R2.POST_TIME>UNIX_TIMESTAMP(R1.update_time)* 1000, 1, 0 )) AS CustomerNotify 
                                                            FROM
                                                                Dg_Chat_Inparams R1
                                                                LEFT JOIN Chat_Message R2 ON R1.Rec_Guid = R2.Ai_Text
                                                                LEFT JOIN Chat_Session R3 ON R2.Chat_Session_Id = R3.Id
                                                                LEFT JOIN ( SELECT Ai_Text, MAX( POST_TIME ) AS maxposttime FROM Chat_Message WHERE Ai_Text = ? AND Length( Chat_User_Id ) > 6 ) R4 ON R4.Ai_Text = R1.Rec_Guid 
                                                            WHERE
                                                                R2.Ai_Text IS NOT NULL 
                                                                AND R1.Rec_Guid = ? 
                                                            GROUP BY
                                                                R1.Rec_Guid,
                                                                R3.Id 
                                                            ) R2 
                                                            SET R1.Chatnumber = R2.Chatnumber,
                                                            R1.Custnumber = R2.Custnumber,
                                                            R1.Staffnumber = R2.Staffnumber ,
                                                            R1.CustomerNotify = R2.CustomerNotify
                                                        WHERE
                                                            R1.Rec_Guid = R2.Rec_Guid 
                                                            AND R1.Rec_Guid = ?'''
                            int totalNum = jt.update(totalSQL, Rec_Guid, Rec_Guid,Rec_Guid);

                            if (update_Num > 0) {
                                log.debug(i + "# Chat_Message_List Map:" + Chat_Message_List.get(i));
                                log.debug(i + "# 更新标记Chat_Message Num:" + update_Num);
                                log.debug(i + "# 更新标记Chat_Message totalNum:" + totalNum);

                            } else {
                                log.debug(i + "# Chat_Message_List Map:" + Chat_Message_List.get(i));
                            }
                        } else {
                            log.warn(i + "# 未找到 找到此前进线历史Chat_Inparams_List:" + Chat_Message_List.get(i));
                        }
                    } else {
                        log.warn(i + "# 未找到 找到用户ID Customer_List:" + Chat_Message_List.get(i));
                    }
                } else {
                    log.warn(i + "# 未找到 SessionID找到对应的坐席:" + Chat_Message_List.get(i));
                }

            }

            outData.put("data", callJson);

        } catch (Exception e) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(outData, e);

        }
        return outData;
    }
}